package com.example.jetpacktest.network;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义的日期解析，gson中使用
 */
public class DateDeserializer implements JsonDeserializer<Date> {

    //private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json != null) {
            final String jsonString = json.getAsString();
            int startIndex = jsonString.indexOf("(");
            int endIndex = jsonString.indexOf(")");
            long time = Long.parseLong(jsonString.substring(startIndex + 1, endIndex));
            try {
                return new Date(time);
            } catch (Exception e) {
                e.printStackTrace();
            }
            final long jsonLong= json.getAsLong();
            try {
                return new Date(jsonLong);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
